package org.geektimes.projects.user.validator.custom;

import org.apache.commons.lang.StringUtils;
import org.geektimes.projects.user.domain.User;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * @author :   chuan
 * @date :   2021/03/15
 */
public class UserValidator implements ConstraintValidator<UserValid, User> {

    private int passwordMin = 6;
    private int passwordMax = 32;

    private String emailRegexp = "^[A-Za-z0-9]+([_\\.][A-Za-z0-9]+)*@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$";

    private String phoneNumberRegexp = "^1[3456789]\\d{9}$";

    @Override
    public void initialize(UserValid constraintAnnotation) {
        if (constraintAnnotation.passwordMin() > 0){
            this.passwordMin = constraintAnnotation.passwordMin();
        }
        if (constraintAnnotation.passwordMax() > 0){
            this.passwordMax = constraintAnnotation.passwordMax();
        }

        if (StringUtils.isNotBlank(constraintAnnotation.emailRegexp())){
            this.emailRegexp = constraintAnnotation.emailRegexp();
        }

        if (StringUtils.isNotBlank(constraintAnnotation.phoneNumberRegexp())){
            this.phoneNumberRegexp = constraintAnnotation.phoneNumberRegexp();
        }
    }

    @Override
    public boolean isValid(User user, ConstraintValidatorContext constraintValidatorContext) {

        Long id = user.getId();
        if (Objects.nonNull(id) && id < 1){
            return false;
        }

        String name = user.getName();
        if (StringUtils.isBlank(name)){
            return false;
        }

        String password = user.getPassword();
        if(StringUtils.isBlank(password)
                || password.length() < passwordMin
                || password.length() > passwordMax){
            return false;
        }

        String email = user.getEmail();
        if (StringUtils.isBlank(email)
                || !email.matches(emailRegexp)){
            return false;
        }

        String phoneNumber = user.getPhoneNumber();
        if (StringUtils.isBlank(phoneNumber)
                || !phoneNumber.matches(phoneNumberRegexp)){
            return false;
        }

        return true;
    }
}
